<template>
  <!-- 父容器 -->
  <div class="container">
    <div class="hello">
      <h1>手机短信查询</h1>
      <br>
      <!--      <el-button type="primary" style="height: 35px;width: 100px" size="small" @click="downloadTemplate">下载导入模板</el-button>-->
      <!-- 下载模板a标签 -->
      <a ref="downloadTemplate" style="display: none" href="手机号查询短信导入模版.xlsx"></a>
      <br>
      <div class="box">
        <div class="chl_box">
          <el-upload
              class="upload-demo"
              drag
              action="#"
              :limit=1
              :auto-upload="false"
              :on-change="handleFileUpload"
              multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <span>秘钥：<el-input v-model="cookie" placeholder="请输入秘钥" style="width: 500px"
                           clearable>秘钥：</el-input></span>
      <br>
      <br>
      <span>
        <el-button type="primary" style="height: 40px;width: 100px" size="small"
                   @click="downloadTemplate">下载导入模板</el-button>
        <el-button style="height: 40px;width: 100px" size="small" type="success" :disabled="disabled" :loading="loading"
                   @click="handleResult"> 查询并导出
      </el-button>
      </span>

      <!--      <el-button style="height: 40px;width: 100px" size="small" type="success" :disabled="disabledExcel"-->
      <!--                 :loading="loading"-->
      <!--                 @click="handleResultExport"> 导出-->
      <!--      </el-button>-->
    </div>
  </div>

</template>

<script>
import {ElMessage} from 'element-plus'
import * as xlsx from "xlsx";

export default {
  name: 'MainIndex',
  props: {
    msg: String
  },
  data() {
    return {
      disabled: true,
      disabledExcel: false,
      cookie: null,
      loading: false,
      tableData: [],
      phoneData: [],
    };
  },
  methods: {
    // 点击模板按钮触发a下载文件
    downloadTemplate() {
      this.$refs.downloadTemplate.dispatchEvent(new MouseEvent('click'))
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    getFileName() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      const hour = now.getHours();
      const minute = now.getMinutes();
      const second = now.getSeconds();
      // 动态文件名
      return `导出文件-${year}-${month}-${day}_${hour}-${minute}-${second}.xlsx`;
    },

    handleResultExport() {
      // const data = [
      //   ["姓名", "年龄", "职业"],
      //   ["张三", 28, "工程师"],
      //   ["李四", 34, "设计师"],
      //   ["王五", 29, "产品经理"]
      // ];
      // this.handleExport(data)
      var sendTime = '2025-02-21T12:23:37.000+0800';
      var split = sendTime.split(".")[0];
      var tempTime = split.replace("T", " ");

    },
    buildMyHeaders() {
      let myHeaders = new Headers();
      myHeaders.append("Cookie", this.cookie);
      myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
      myHeaders.append("content-type", "application/json");
      myHeaders.append("Accept", "*/*");
      myHeaders.append("Host", "paas.longhu.net");
      myHeaders.append("Connection", "keep-alive");
      return myHeaders;
    },

    buildUrlParam(mobile) {
      let mobileParam = mobile;
      const now = new Date();
      const pastTime = new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000); // 计算过去的时间
      let startTimeParam = this.formatDate(pastTime);
      let endTimeParam = this.formatDate(now);
      let statusParam = '';
      let templateTypeParam = '';
      let productParam = '';
      let pageNumParam = 1;
      let pageSizeParam = 100;

      let urlParam = 'mobile={mobileParam}&startTime={startTimeParam}&endTime={endTimeParam}&pageNum={pageNumParam}&status&templateType&pageSize={pageSizeParam}&product'
      return urlParam.replace("{mobileParam}", mobileParam)
          .replace("{startTimeParam}", startTimeParam)
          .replace("{endTimeParam}", endTimeParam)
          .replace("{pageNumParam}", pageNumParam)
          .replace("{pageSizeParam}", pageSizeParam)
    },

    handleResult() {
      this.loading = true;
      if (this.phoneData.length === 0) {
        ElMessage.error('手机号是空的，请检查导入的Excel')
        this.loading = false;
        return
      }
      // 验证手机号格式
      for (let i = 0; i < this.phoneData.length; i++) {
        if (!this.validatePhoneNumber(this.phoneData[i])) {
          ElMessage.error('手机号长度不正确：' + this.phoneData[i])
          this.loading = false;
          return
        }
      }

      if (this.cookie === null) {
        ElMessage.error('秘钥不能为空!');
        this.loading = false;
        return;
      }
      if (this.phoneData.length > 1000) {
        ElMessage.error('数据量过大，最大仅支持1000条，请重新选择文件');
        this.loading = false;
        return;
      }

      // 创建一个工作表数据
      const excelArray = [["手机号码", "发送时间", "短信通道", "发送产品", "特征参数"]];

      const fetchAndProcessData = async (item) => {
        let requestOptions = {method: 'POST', headers: this.buildMyHeaders(), redirect: 'follow'};
        let urlParam = this.buildUrlParam(item);

        try {
          const response = await fetch("https://paas.longhu.net/v1/openApi/notification/filterSendDetailList?" + urlParam, requestOptions);
          const result = await response.json();
          if (result.code === '200') {
            for (let resData of result.data.sendRecordDtoList) {
              let jsonString = resData.sendDetail;
              let obj = JSON.parse(jsonString);
              if (obj.tempId === '10264' || obj.tempId === '10511') {
                var sendTime = resData.sendTime;
                var split = sendTime.split(".")[0];
                var tempTime = split.replace("T", " ");
                // 2025-02-21T12:23:37.000+0800
                excelArray.push([item, tempTime, resData.provider, resData.customer, obj.tempId]);
              }
            }
          }
        } catch (error) {
          console.error('error', error);
        }
      };

      const processAllData = async () => {
        for (let item of this.phoneData) {
          await fetchAndProcessData(item);
        }
        this.handleExport(excelArray);
        this.loading = false;
      };

      processAllData();
    },


    //导出excel
    handleExport(excelData) {
      ElMessage.success('查询完毕,导出Excel中,请稍等...')
      console.log("Excel数据：", excelData)
      if (!excelData) {
        ElMessage.error('导出的Excel数据是空的!')
        return
      }

      // 将数据转换为工作表对象
      const ws = xlsx.utils.aoa_to_sheet(excelData);
      // 设置列宽
      ws['!cols'] = excelData[0].map(() => ({wch: 20}));

      // 创建一个新的工作簿并添加工作表
      const wb = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(wb, ws, "Sheet1");

      // 导出Excel文件
      xlsx.writeFile(wb, this.getFileName());
    },
    validatePhoneNumber(phoneNumber) {
      return phoneNumber.length === 11;
    },

    handleFileUpload(event) {
      ElMessage.info('开始读取手机号数据')
      this.phoneData = []
      const file = event.raw;

      const reader = new FileReader();
      // 处理文件内容
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = xlsx.read(data, {type: 'array'});

        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = xlsx.utils.sheet_to_json(worksheet, {header: 1});

        // 提取文件内容
        jsonData.slice(1).forEach(row => {
          if (!row) {
            return
          }
          if (!row[0]) {
            return
          }
          let phone = row[0].toString().replace(/\s+/g, "");
          console.log("读取到手机号：", phone)
          this.phoneData.push(phone)
        })
      };
      // 读取文件内容
      reader.readAsArrayBuffer(file);
      ElMessage.success('读取手机号数据成功')
      this.disabled = false
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
:deep(.el-upload-list__item-name) {
  padding: 5px 0;
  font-size: 20px;
}

.hello {
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  margin: 8px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

.box {
  width: 450px;
  height: 150px;
  position: relative;
}

.chl_box {
  width: 450px;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

* {
  margin: 0;
  padding: 0;
}

/* 父容器样式 */
.container {
  height: 400px;
  margin-top: 50px;
}


</style>
